<script setup lang="ts">
import { computed, reactive, ref, watch } from 'vue'
// import { navigateToUrl } from 'single-spa'
import { useStore } from 'stores/store'
// import { useRoute/* , useRouter */ } from 'vue-router'
import { i18n } from 'boot/i18n'
import OpenAI from 'openai'

// @ts-ignore
import siteSetting from '@cnic/site-setting'
// @ts-ignore
import { useStoreMain } from '@cnic/main'
import { QScrollArea } from 'quasar'

const props = defineProps({
  chatId: {
    type: String,
    required: true
  },
  initMessage: {
    type: String,
    required: false
  },
  initModel: {
    type: String,
    required: false
  }
})
// const emits = defineEmits(['change', 'delete'])

const { tc } = i18n.global
const store = useStore()
// const route = useRoute()
// const router = useRouter()

console.log(props)

const scrollAreaRef = ref<QScrollArea>()

const model = reactive({
  models: computed(
    () => Object.values(store.tables.modelTable.byId)
      .filter(item => item.is_active)
  ),
  selectionModel: props?.initModel || '',

  // 当前chat的所有消息记录
  messages: [] as Record<string, unknown>[],

  input: ''
})

// Scroll Observer 实现停止自动滚动

// scroll to position
const scrollToBottom = () => {
  scrollAreaRef!.value.setScrollPercentage('vertical', 1, 100)
}

// 选择默认model
const chooseModel = () => {
  model.selectionModel = props?.initModel || model.models[0].name || ''
}
if (model.models.length > 0) {
  // console.log('setup choose service')
  chooseModel()
} else {
  watch(store.tables.modelTable, () => {
    if (store.tables.modelTable.status !== 'loading') {
      chooseModel()
    }
  })
}

// 发送消息
const sendMessage = async (input: string) => {
  // append msg
  model.messages.push({
    role: 'user',
    content: input
  })

  // clear input
  model.input = ''

  // send
  // get jwt token from @cnic/main's store
  const storeMain = useStoreMain()
  const client = new OpenAI({
    dangerouslyAllowBrowser: true,
    baseURL: 'https://' + siteSetting.api_chat + '/api/v1/',
    apiKey: storeMain.items.tokenAccess as string // This is the default and can be omitted
  })

  const response = await client.chat.completions.create({
    model: model.selectionModel,
    messages: [
      {
        role: 'system',
        content: 'You are a helpful assistant.'
      },
      {
        role: 'user',
        content: input
      }
    ],
    stream: true
  })

  // new message object
  model.messages.push({
    role: 'assistant',
    content: ''
  })

  const currentMessage = model.messages[model.messages.length - 1]
  for await (const chunk of response) {
    currentMessage.content += chunk.choices[0]?.delta?.content || ''

    scrollToBottom()
  }
}

// 初次进入，带着第一个消息进来
if (props.initMessage) {
  sendMessage(props.initMessage)
}

</script>

<template>
  <div style="height: calc(100vh - 60px);">

    <!-- 悬浮chat title   -->
    <q-page-sticky class="bg-white"
                   style="height: 75px; z-index: 1; mask-image: linear-gradient(to bottom, black 70%, transparent 100%);"
                   expand
                   position="top"
                   :offset="[0, 60]">
      <div class="text-weight-bold" style="font-size: 15px;">
        问答标题 id: {{ chatId }}
      </div>
    </q-page-sticky>

    <q-scroll-area ref="scrollAreaRef" class="fit" visible>
      <div class="column items-center justify-center" style="padding-top: 75px; margin-bottom: 150px;">

        {{initMessage}}

        <div v-for="(message, index) in model.messages" :key="index" class="col-auto row full-width justify-center">

          <div v-if="message.role === 'user'" class="col-auto row full-width justify-end"
               style="max-width: 800px; margin-bottom: 45px;">
            <div class="right-msg-frame">
              {{ message.content }}
            </div>
          </div>

          <div v-if="message.role ==='assistant'" class="col-auto row full-width justify-start"
               style="max-width: 800px; margin-bottom: 45px;">
            <q-avatar class="col-auto" style="border: 1px solid #ccc; border-radius: 50%;" size="35px">
              <img :src="require('assets/svg/icon_deepseek_color.svg')"/>
            </q-avatar>

            <div class="col column">
              <div class="col left-msg-frame">
                {{ message.content }}
              </div>
              <div class="col-auto row" style="padding: 0 10px; margin-top: 5px;">
                <q-btn class="col-auto"
                       icon="content_copy"
                       color="grey-7"
                       flat
                       dense
                       size="sm"
                       padding="non"
                       :ripple="false">
                  <q-tooltip>
                    {{ tc('复制') }}
                  </q-tooltip>
                </q-btn>

                <q-btn class="col-auto"
                       icon="autorenew"
                       color="grey-7"
                       flat
                       dense
                       size="sm"
                       padding="non"
                       :ripple="false">
                  <q-tooltip>
                    {{ tc('重新生成') }}
                  </q-tooltip>
                </q-btn>
              </div>
            </div>
          </div>

        </div>

      </div>
    </q-scroll-area>

    <!-- 悬浮input -->
    <q-page-sticky expand position="bottom">

      <div class="column full-width justify-center bg-white" style="max-width: 800px;">

        <div class="row items-center justify-end">
          <q-btn class="q-ma-sm"
                 outline
                 dense
                 round
                 color="grey-5"
                 icon="expand_more"
                 :ripple="false"
                 @click="scrollToBottom">
          </q-btn>

        </div>

        <div class="col-auto column full-width input-frame ">
          <q-input class="col"
                   v-model="model.input"
                   :placeholder="tc('给 DeepSeek 发送消息')"
                   autogrow
                   dense
                   borderless
                   @keydown.enter.prevent="sendMessage(model.input)"/>

          <div class="col-auto row">
            <div class="col row">
              <q-btn v-for="(item, index) in model.models" :key="index"
                     class="text-caption q-mr-xs"
                     :class="model.selectionModel === item?.name ? 'button-selected' : 'button-unselected'"
                     :ripple="false"
                     rounded
                     unelevated dense
                     no-caps
                     @click="model.selectionModel = item?.name">
                {{ item.name }}
              </q-btn>
            </div>
            <div class="col-auto row items-center q-gutter-xs">
              <!--开启新对话-->
              <q-btn style="background: #DBEAFE; color: #1976D2; border-radius: 9px !important;"
                     icon="post_add"
                     unelevated
                     dense
                     :ripple="false"
                     to="/my/chat/new">
                <div class="">
                  {{ tc('开启新对话') }}
                </div>
              </q-btn>
              <!--发送新message-->
              <q-btn class="bg-grey-5 text-white"
                     icon="arrow_upward"
                     :ripple="false"
                     flat
                     round
                     dense
                     no-caps
                     @click="sendMessage(model.input)"/>
            </div>
          </div>
        </div>

        <div class="col-auto row full-width items-center justify-center q-mr-xs text-grey">
          {{ tc('内容由 AI 生成，请仔细甄别') }}
        </div>
      </div>

    </q-page-sticky>
  </div>
</template>

<style lang="scss" scoped>
.button-selected {
  background-color: #DBEAFE;
  color: #1976D2;
}

.button-unselected {
  background-color: white;
  color: black;
}

.left-msg-frame {
  max-width: 750px;
  line-height: 28px;
  padding: 0 10px;
  white-space: pre-wrap;
  word-break: break-word;
}

.right-msg-frame {
  max-width: 610px;
  background-color: #eff6ff;
  border-radius: 14px;
  line-height: 28px;
  padding: 5px 15px;
  white-space: pre-wrap;
  word-break: break-word;
}

.input-frame {
  min-height: 110px;
  padding: 10px;
  background-color: rgb(243 244 246);
  box-shadow: 0px 0px 0px .5px #dce0e9;
  border-radius: 24px;
}
</style>
